<template>
  <div class="container">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card tweets-users-card">
          <div slot="header" class="card-header clearfix">
            <h5 class="title pull-left">选择用户</h5>
          </div>

          <div class="card-wrapper">
            <el-form ref="filterForm" :model="listQuery" class="filter-container">
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item prop="name">
                    <el-input v-model="listQuery.name" size="small" placeholder="医生姓名" clearable @keyup.enter.native="handleFilter" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="openid">
                    <el-input v-model="listQuery.openid" size="small" placeholder="OpenId" clearable @keyup.enter.native="handleFilter" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="tel">
                    <el-input v-model="listQuery.tel" size="small" placeholder="手机号码" clearable @keyup.enter.native="handleFilter" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item prop="cluster">
                    <el-select v-model="listQuery.cluster" size="small" placeholder="所属群组" clearable style="width:100%" @change="handleFilter">
                      <el-option v-for="item in clusterOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="deparrment">
                    <el-select v-model="listQuery.deparrment" size="small" placeholder="科室名称" filterable clearable style="width:100%" @change="handleFilter">
                      <el-option v-for="item in deparpmentOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="type">
                    <el-select
                      v-model="listQuery.type"
                      size="small"
                      placeholder="请选择用户类型"
                      filterable
                      clearable
                      style="width:100%"
                      @change="handleFilter"
                    >
                      <el-option
                        v-for="item in typeOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-form-item>
                    <el-button
                      size="small"
                      type="primary"
                      icon="el-icon-search"
                      @click="handleFilter"
                    >筛选</el-button>
                    <el-button
                      size="small"
                      @click="resetFilter"
                    >重置</el-button>
                    <el-divider direction="vertical" />
                    <el-button
                      size="small"
                      type="success"
                      icon="el-icon-plus"
                      @click="addSelectedUsers"
                    >添加已选用户</el-button>
                    <el-button
                      size="small"
                      type="warning"
                      icon="el-icon-plus"
                      @click="addSelectedFilterUsers"
                    >添加所选类型</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <el-table
              ref="usersTable"
              v-loading="listLoading"
              :data="list"
              element-loading-text="Loading"
              stripe
              fit
              highlight-current-row
              height="1000"
              row-key="id"
              @selection-change="userSelectionChange"
            >
              <el-table-column
                fixed
                type="selection"
                reserve-selection
                width="50"
                align="center"
              />
              <el-table-column label="姓名" width="130">
                <template slot-scope="scope">
                  {{ scope.row.name }}
                </template>
              </el-table-column>
              <el-table-column label="VeevaCode">
                <template slot-scope="scope">
                  {{ scope.row.veeva_code }}
                </template>
              </el-table-column>
              <el-table-column label="医院名称">
                <template slot-scope="scope">
                  {{ scope.row.hospname }}
                </template>
              </el-table-column>
              <el-table-column label="科室名称" width="130" align="center">
                <template slot-scope="scope">
                  {{ scope.row.adfname }}
                </template>
              </el-table-column>
              <el-table-column label="所属群组" width="160" align="center">
                <template slot-scope="scope">
                  <el-tag
                    v-if="!_.isNil(scope.row.clusterName)"
                    effect="plain"
                    size="mini"
                  >{{ scope.row.clusterName }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="用户类型" width="100" align="center">
                <template slot-scope="scope">
                  <el-tag
                    v-if="!_.isEmpty(scope.row.typename)"
                    type="success"
                    effect="plain"
                    size="mini"
                  >{{ scope.row.typename }}</el-tag>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" small layout="total, prev, pager, next" :auto-scroll="false" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="fetchUsers" />
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="box-card tweets-users-card">
          <div slot="header" class="card-header clearfix">
            <h5 class="title pull-left">已选用户</h5>
          </div>

          <div class="card-wrapper">
            <el-form ref="selectedFilterForm" :model="selectedListQuery" class="filter-container">
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item prop="name">
                    <el-input v-model="selectedListQuery.name" size="small" placeholder="医生姓名" clearable @keyup.enter.native="handleSelectedFilter" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="openid">
                    <el-input v-model="selectedListQuery.openid" size="small" placeholder="OpenId" clearable @keyup.enter.native="handleSelectedFilter" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="tel">
                    <el-input v-model="selectedListQuery.tel" size="small" placeholder="手机号码" clearable @keyup.enter.native="handleSelectedFilter" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item prop="cluster">
                    <el-select v-model="selectedListQuery.cluster" size="small" placeholder="所属群组" clearable style="width:100%" @change="handleSelectedFilter">
                      <el-option v-for="item in clusterOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="deparrment">
                    <el-select v-model="selectedListQuery.deparrment" size="small" placeholder="科室名称" filterable clearable style="width:100%" @change="handleSelectedFilter">
                      <el-option v-for="item in deparpmentOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="type">
                    <el-select
                      v-model="selectedListQuery.type"
                      size="small"
                      placeholder="请选择用户类型"
                      filterable
                      clearable
                      style="width:100%"
                      @change="handleSelectedFilter"
                    >
                      <el-option
                        v-for="item in typeOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-form-item>
                    <el-button
                      size="small"
                      type="primary"
                      icon="el-icon-search"
                      @click="handleSelectedFilter"
                    >筛选</el-button>
                    <el-button
                      size="small"
                      @click="resetSelectedFilter"
                    >重置</el-button>
                    <el-divider direction="vertical" />
                    <el-button
                      size="small"
                      type="warning"
                      :loading="repeatBtnLoading"
                      :disabled="repeatBtnLoading"
                      @click="checkTaskOpenid"
                    >校验重复</el-button>
                    <el-button
                      size="small"
                      type="warning"
                      :loading="removeBtnLoading"
                      :disabled="removeBtnLoading"
                      @click="removeLimitOpenid"
                    >移除超发次数用户</el-button>
                    <el-button
                      size="small"
                      type="danger"
                      icon="el-icon-delete"
                      @click="removeAllSelectedUsers"
                    >移除所有</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <el-table
              v-loading="selectedListLoading"
              :data="selectedList"
              element-loading-text="Loading"
              stripe
              fit
              highlight-current-row
              height="1000"
            >
              <el-table-column label="姓名" width="130">
                <template slot-scope="scope">
                  {{ scope.row.name }}
                </template>
              </el-table-column>
              <el-table-column label="次数" width="80" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.times >= 1" class="text-danger">{{ scope.row.times }}</span>
                  <span v-else class="text-success">{{ scope.row.times }}</span>
                  / 1
                </template>
              </el-table-column>
              <el-table-column label="OpenId">
                <template slot-scope="scope">
                  {{ scope.row.openid }}
                </template>
              </el-table-column>
              <el-table-column label="科室名称" width="130" align="center">
                <template slot-scope="scope">
                  {{ scope.row.departmentName }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    size="mini"
                    plain
                    @click="removeUser(scope.row.id)"
                  >移除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="selectedTotal > 0" small layout="total, prev, pager, next" :auto-scroll="false" :total="selectedTotal" :page.sync="selectedListQuery.page" :limit.sync="selectedListQuery.size" @pagination="fetchSelectedUsers" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div class="text-center mt40">
      <el-button @click="prevStep">上一步</el-button>
      <el-button
        type="primary"
        @click="submitTweets"
      >提 交</el-button>
    </div>

    <el-dialog
      title="以下用户有重复，OpenId为："
      :visible.sync="repeatOpenid"
      width="50%"
      center
    >
      <ul class="repeat-openid-list">
        <li
          v-for="(item, index) in repeatOpenidList"
          :key="index"
        >{{ item.openid }}</li>
      </ul>
      <div class="text-warning text-center mt40">请在列表中找到该用户，进行移除操作</div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsersList
} from '@/api/users'
import {
  getDepartments,
  getUserType,
  getCluster
} from '@/api/baseData'
import {
  getTemplatesTaskUsers,
  templatesTaskCheckOpenid,
  addTemplatesTaskUsers,
  removeTemplatesTaskUsers,
  addFilterTemplatesTaskUsers,
  removeAllSelectedUsers,
  removeLimitOpenid
} from '@/api/templatesMsgs'
import Pagination from '@/components/Pagination'

export default {
  name: 'TemplateMsgTweetsStep2',
  components: {
    Pagination
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      taskId: '',
      list: [],
      listLoading: false,
      total: 0,
      listQuery: {
        name: undefined,
        type: undefined,
        deparrment: undefined,
        openid: undefined,
        tel: undefined,
        cluster: undefined,
        attention: 1,
        state: 3,
        page: 1,
        size: 30
      },
      clusterOptions: [],
      deparpmentOptions: [],
      typeOptions: [],
      checkedList: [],
      selectedList: null,
      selectedListLoading: false,
      selectedTotal: 0,
      selectedListQuery: {
        name: undefined,
        type: undefined,
        deparrment: undefined,
        openid: undefined,
        tel: undefined,
        cluster: undefined,
        page: 1,
        size: 30
      },
      repeatOpenid: false,
      repeatBtnLoading: false,
      repeatOpenidList: [],
      removeBtnLoading: false
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.taskId = id
      this.selectedListQuery.taskId = id
    }
    this.fetchCluster()
    this.fetchDepartments()
    this.fetchUserType()
    this.fetchUsers()
    this.fetchSelectedUsers()
  },
  methods: {
    fetchCluster() {
      getCluster().then(response => {
        // console.log(response)
        this.clusterOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchDepartments() {
      getDepartments().then(response => {
        // console.log(response)
        this.deparpmentOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchUserType() {
      getUserType().then(response => {
        // console.log(response)
        this.typeOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchUsers() {
      this.listLoading = true
      getUsersList(this.listQuery).then(response => {
        // console.log(response)
        if (this._.isEmpty(response.data)) {
          this.list = []
        } else {
          this.list = response.data
        }
        this.total = response.total
        this.listLoading = false
      }).catch(err => {
        console.log(err)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.list = []
      this.fetchUsers()
    },
    resetFilter() {
      this.$refs.filterForm.resetFields()
      this.handleFilter()
    },
    addSelectedUsers() {
      // console.log(this.checkedList)
      if (this._.isEmpty(this.checkedList)) {
        this.$message({
          type: 'error',
          message: '请先选择用户'
        })
      } else {
        addTemplatesTaskUsers({
          taskId: this.taskId,
          userIds: this.checkedList.join(',')
        }).then(response => {
          // console.log(response)
          if (response.rtncode === 200) {
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            this.handleSelectedFilter()
            this.$refs.usersTable.clearSelection()
          } else {
            this.$message({
              type: 'error',
              message: '添加失败，请重新添加'
            })
          }
        }).catch(err => {
          console.log(err)
        })
      }
    },
    addSelectedFilterUsers() {
      this.$confirm('确认添加所选类型?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectedListLoading = true
        addFilterTemplatesTaskUsers({
          taskId: this.taskId,
          type: this.listQuery.type,
          deparrment: this.listQuery.deparrment,
          cluster: this.listQuery.cluster,
          attention: 1,
          state: 3
        }).then(response => {
          // console.log(response)
          if (response.rtncode === 200) {
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            this.handleSelectedFilter()
            this.$refs.usersTable.clearSelection()
          } else {
            this.$message({
              type: 'error',
              message: '添加失败，请重新添加'
            })
          }
        }).catch(err => {
          console.log(err)
        })
      })
    },
    userSelectionChange(val) {
      // console.log(this._.map(val, 'id'))
      this.checkedList = this._.map(val, 'id')
    },
    fetchSelectedUsers() {
      this.selectedListLoading = true
      getTemplatesTaskUsers(this.selectedListQuery).then(response => {
        // console.log(response)
        this.selectedList = response.data
        this.selectedTotal = response.total
        this.selectedListLoading = false
      }).catch(err => {
        console.log(err)
      })
    },
    handleSelectedFilter() {
      this.selectedListQuery.page = 1
      this.selectedList = []
      this.fetchSelectedUsers()
    },
    resetSelectedFilter() {
      this.$refs.selectedFilterForm.resetFields()
      this.handleSelectedFilter()
    },
    checkTaskOpenid() {
      this.repeatBtnLoading = true
      templatesTaskCheckOpenid({
        taskId: this.taskId
      }).then(response => {
        // console.log(response)
        const { data } = response
        if (!this._.isEmpty(data)) {
          this.repeatOpenidList = data
          this.repeatOpenid = true
        } else {
          this.$message({
            type: 'info',
            message: '暂无重复用户'
          })
        }
        this.repeatBtnLoading = false
      }).catch(err => {
        console.log(err)
        this.repeatBtnLoading = false
      })
    },
    removeUser(id) {
      this.$confirm('是否移除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeTemplatesTaskUsers({ id }).then(response => {
          // console.log(response)
          this.fetchSelectedUsers()
          this.$notify({
            title: '成功',
            message: '移除成功',
            type: 'success',
            duration: 2000
          })
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消移除'
        })
      })
    },
    removeAllSelectedUsers(id) {
      this.$confirm('是否移除所有?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeAllSelectedUsers({
          taskId: this.taskId
        }).then(response => {
          // console.log(response)
          this.fetchSelectedUsers()
          this.$notify({
            title: '成功',
            message: '移除成功',
            type: 'success',
            duration: 2000
          })
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消移除'
        })
      })
    },
    removeLimitOpenid() {
      this.$confirm('是否移除所有超过发送次数的用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectedListLoading = true
        this.removeBtnLoading = true
        removeLimitOpenid({
          taskId: this.taskId
        }).then(response => {
          // console.log(response)
          this.fetchSelectedUsers()
          this.$notify({
            title: '成功',
            message: '已成功移除所有超过发送次数的用户',
            type: 'success',
            duration: 2000
          })
          this.selectedListLoading = false
          this.removeBtnLoading = false
        }).catch(err => {
          console.log(err)
          this.removeBtnLoading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消移除'
        })
      })
    },
    prevStep() {
      this.$router.push(`/template-msgs/edit/${this.taskId}?step=1`)
    },
    submitTweets() {
      console.log('submit')
      this.$router.push('./../list')
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 40px 80px;
}
.tweets-users-card .card-wrapper {
  height: 1174px;
  .pagination-container {
    line-height: normal;
    padding: 16px 0 0;
  }
}
.repeat-openid-list {
  line-height: 30px;
}
</style>
